package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService baseAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu描述图片 pms_spu_info_desc
        List<String> decriptImgUrls = vo.getDecript();
        Long spuId = spuInfoEntity.getId();
        if (!CollectionUtils.isEmpty(decriptImgUrls)) {
            String urlsStr = String.join(",", decriptImgUrls);
            SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
            descEntity.setSpuId(spuId);
            descEntity.setDecript(urlsStr);
            descService.saveSpuInfoDesc(descEntity);
        }


        //3.保存spu图片集 pms_spu_images
        spuImagesService.saveSpuImages(vo.getImages(), spuId);

        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            List<ProductAttrValueEntity> baseAttrEntities = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity entity = new ProductAttrValueEntity();
                entity.setSpuId(spuId);
                entity.setAttrId(attr.getAttrId());
                AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                if (attrEntity != null) {
                    entity.setAttrName(attrEntity.getAttrName());
                }
                entity.setAttrValue(attr.getAttrValues());
                entity.setQuickShow(attr.getShowDesc());
                return entity;
            }).collect(Collectors.toList());
            baseAttrValueService.saveBaseAttrValues(baseAttrEntities);
        }


        // 5.保存spu积分信息 gulimall_sms -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        if (bounds != null) {
            SpuBoundTo spuBoundTo = new SpuBoundTo();
            BeanUtils.copyProperties(bounds, spuBoundTo);
            spuBoundTo.setSpuId(spuId);
            R r = couponFeignService.saveSpuBounds(spuBoundTo);
            if (r.getCode() != 0) {
                log.error("远程保存spu积分信息失败");
            }
        }


        //6.保存当前spu对应的所有sku信息:

        //6.1 sku基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                List<Images> images = item.getImages();
                String skuDefaultImg = null;
                if (!CollectionUtils.isEmpty(images)) {
                    for (Images image : images) {
                        if (image.getDefaultImg() == 1) {
                            skuDefaultImg = image.getImgUrl();
                            break;
                        }
                    }
                }
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //6.2 sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<Images> skuImages = item.getImages();
                if (!CollectionUtils.isEmpty(skuImages)) {
                    List<SkuImagesEntity> skuImagesEntities = skuImages.stream()
                            .filter(img -> !StringUtils.isEmpty(img.getImgUrl()))
                            .map(skuImg -> {
                                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                skuImagesEntity.setSkuId(skuId);
                                skuImagesEntity.setImgUrl(skuImg.getImgUrl());
                                skuImagesEntity.setDefaultImg(skuImg.getDefaultImg());
                                return skuImagesEntity;
                            }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntities);
                }

                //6.3 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> skuAttrs = item.getAttr();
                if (!CollectionUtils.isEmpty(skuAttrs)) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = skuAttrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, saleAttrValueEntity);
                        saleAttrValueEntity.setSkuId(skuId);
                        return saleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }

                //6.4 sku的优惠/满减等信息
                //    gulimall_sms -> sms_sku_ladder\
                //                    sms_sku_full_reduction\
                //                    sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        /**
         * status:
         * key:
         * brandId: 0
         * catelogId: 0
         */
        String status = (String) params.get("status");
        queryWrapper.eq(!StringUtils.isEmpty(status), SpuInfoEntity::getPublishStatus, status);

        String key = (String) params.get("key");
        queryWrapper.and(!StringUtils.isEmpty(key),
                wrapper -> wrapper.eq(SpuInfoEntity::getId, key)
                        .or()
                        .like(SpuInfoEntity::getSpuName, key));

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}